<template>
  <div class="cart-container">
    <LayoutHeaderTitle :title="cartTitle">
      <template #right>
        <div :class="manageClass" @click="changeManageMode">
          管理
          <van-icon name="cross" v-show="isManage" />
        </div>
      </template>
    </LayoutHeaderTitle>
    <div v-if="list.length">
      <div class="cart-list">
        <ul>
          <li v-for="item in list" :key="item.b_id">
            <div class="head">
              <van-checkbox
                :value="getStoreChecked(item.b_id)"
                @click="changeStoreChecked(item.b_id)"
              />
              <nuxt-link :to="item.b_id | storeUrl">
                {{ item.b_name }} <van-icon name="arrow" />
              </nuxt-link>
            </div>
            <div
              :class="['item', isDisableGoods(c)]"
              v-for="c in item.list"
              :key="c.cart_id"
            >
              <van-checkbox
                class="checkbox"
                :value="isDisableGoods(c) && !isManage ? false : c.checked"
                :disabled="isDisableGoods(c) && !isManage"
                @click="
                  (isDisableGoods(c) && !isManage) || changeSingleChecked(c)
                "
              />
              <div class="info">
                <nuxt-link :to="c.g_id | goodsUrl">
                  <img :src="c.g_src | formatSrc" :alt="c.g_name" />
                </nuxt-link>
                <div class="content">
                  <nuxt-link :to="c.g_id | goodsUrl" class="text-over2 name">
                    {{ c.g_name }}
                  </nuxt-link>
                  <div v-if="isDisableGoods(c)">
                    <p class="spec">
                      当前规格或者商品已失效，请重新选择
                    </p>
                  </div>
                  <div v-else>
                    <p class="spec text-over" @click="getSpecs(c)">
                      {{ c.spec_name }}
                    </p>
                    <div class="set-num">
                      <span class="price">
                        <small> ￥</small>
                        <big>
                          {{ c.discounted_price || c.sell_price }}
                        </big>
                      </span>
                      <van-stepper
                        :value="c.num"
                        :min="1"
                        :max="c.stock"
                        async-change
                        @change="e => cartNumChange(c, e)"
                        disable-input
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>

      <div class="total">
        <van-checkbox :value="allChecked" @click="changeAllChecked" />
        <div class="result" v-show="!isManage">
          <span>
            总计：
            <small>￥</small>
            <big>{{ allPrice }}</big>
          </span>
          <van-button
            class="btn"
            round
            color="linear-gradient(to right, #ff6034, #ee0a24)"
            @click="onButtonClick('order')"
          >
            结算
          </van-button>
        </div>
        <div class="delete" v-show="isManage">
          <span @click="onButtonClick('like')">移入收藏夹</span>
          <van-button
            class="btn"
            round
            type="danger"
            @click="onButtonClick('delete')"
          >
            删除
          </van-button>
        </div>
      </div>
    </div>

    <GoodsEmpty v-else img="cart" title="你还未添加商品到购物车哦" />
    <GoodsSpecsPop
      v-model="showGoodsPop"
      :img="choseGoodsSpecs.g_src | formatSrc"
      :specs="chooseSpecs"
      :goodsName="choseGoodsSpecs.g_name"
      type="update"
      @input="closeModal"
      @updateGoodsSpecs="updateGoodsSpecs"
    />
  </div>
</template>
<script>
export default {
  middleware: "authenticated",
  async asyncData({ app }) {
    try {
      const { status, data } = await app.$apiGetCart();
      if (status === 0) {
        return { list: data };
      }
    } catch (error) {}
    return { list: [] };
  },
  data: () => ({
    list: [], // 购物车列表
    showGoodsPop: false, // 显示修改规格弹窗
    choseGoodsSpecs: {}, //  选中规格信息
    chooseSpecs: [], // 修改的规格信息
    isManage: false // 管理模式
  }),
  computed: {
    // 购物车数量
    cartTitle() {
      let num = this.list.reduce((a, c) => {
        const l = c.list.filter(
          i => i.g_status === "正常" && i.spec_status === "正常"
        );
        return a + l.length;
      }, 0);
      return `购物车(${num})`;
    },
    // 是否全部选中
    allChecked() {
      if (this.list.length === 0) {
        return false;
      }
      return this.list.every(i =>
        i.list
          .filter(item => !this.isDisableGoods(item))
          .every(item => item.checked)
      );
    },
    // 获取选中给商品价格
    allPrice() {
      const total = this.list.reduce(
        (sum, item) =>
          sum +
          item.list
            .filter(i => !this.isDisableGoods(i))
            .reduce((listSum, i) => {
              if (i.checked) {
                return listSum + i.num * (i.discounted_price || i.sell_price);
              }
              return listSum;
            }, 0),
        0
      );
      return total.toFixed(2);
    },
    // 右上角 动态 class
    manageClass() {
      if (this.isManage) {
        return "right-botton active";
      }
      return "right-botton";
    }
  },
  methods: {
    // 获取店铺 是否被选中， 依据：该店铺的列表是否都被选中
    getStoreChecked(b_id) {
      const store = this.list.find(item => item.b_id === b_id);
      if (!store || !store.list) {
        return false;
      }
      const filterFn = this.isManage
        ? Boolean
        : item => !this.isDisableGoods(item);
      const list = store.list.filter(filterFn);
      return list.length && list.every(item => item.checked);
    },
    // 修改店铺下的状态商品选中状态
    changeStoreChecked(b_id) {
      const isChecked = this.getStoreChecked(b_id);
      const store = this.list.find(item => item.b_id === b_id);

      store.list.forEach(
        item =>
          (!this.isDisableGoods(item) || this.isManage) &&
          (item.checked = !isChecked)
      );
    },
    // 修改所有购物车选中状态
    changeAllChecked() {
      const isChecked = this.allChecked;
      const filterFn = this.isManage
        ? Boolean
        : item => !this.isDisableGoods(item);
      this.list.forEach(item => {
        item.list.filter(filterFn).forEach(i => (i.checked = !isChecked));
      });
    },
    // 修改单个购物车选中状态
    changeSingleChecked(cart) {
      cart.checked = !cart.checked;
    },
    // 点击获取商品规格
    getSpecs(info) {
      if (info.g_status !== "正常") {
        return;
      }
      const loading = this.$helperLoadding();
      this.choseGoodsSpecs = info;
      this.$apiGetSpecs({ g_id: info.g_id })
        .then(res => {
          const { status, data } = res;
          if (status === 0) {
            this.chooseSpecs = data;
          }
        })
        .finally(() => {
          loading.clear();
          this.showGoodsPop = true;
        });
    },
    // 子组件选择后 确认修改规格
    updateGoodsSpecs(specInfo) {
      this.$apiUpdateCartSpecs({
        newInfo: specInfo,
        oldInfo: this.choseGoodsSpecs
      }).then(res => {
        const { status } = res;
        if (status === 0) {
          this.getCartList().then(() => {
            this.closeModal(false);
          });
        }
      });
    },
    // 关闭 商品规格组件
    closeModal(bool) {
      this.showGoodsPop = bool;
      if (!bool) {
        this.choseGoodsSpecs = {};
      }
    },
    // 当个购物车状态
    isDisableGoods({ spec_status, stock, g_status }) {
      return (
        (spec_status !== "正常" || stock === 0 || g_status !== "正常") &&
        "disabled"
      );
    },
    // 修改管理模式
    changeManageMode() {
      if (this.isManage) {
        this.list.forEach(item => {
          item.list
            .filter(this.isDisableGoods)
            .forEach(i => (i.checked = false));
        });
      }
      this.isManage = !this.isManage;
    },
    // 点击移入
    onButtonClick(type) {
      const chooseCart = [];
      this.list.forEach(item => {
        if (item.list && item.list.length) {
          item.list.forEach(item => {
            if (item.checked) {
              chooseCart.push(item);
            }
          });
        }
      });
      if (chooseCart.length === 0) {
        return this.$toast({
          message: "你还未选中购物车里的商品",
          type: "fail"
        });
      }
      const orderList = this.list
        .map(i => ({
          ...i,
          list: i.list.filter(c => c.checked)
        }))
        .filter(i => i.list.length);
      const fnKey = {
        like: "addToLike",
        delete: "delCart",
        order: "goOrder"
      };
      const fn = this[fnKey[type]];
      if (type === "order") {
        return fn(orderList);
      }
      const loading = this.$helperLoadding();
      fn(chooseCart).then(() => {
        this.getCartList()
          .then(() => {
            this.isManage = false;
          })
          .finally(() => {
            loading.clear();
          });
      });
      // console.log(type, chooseCart);
    },
    // 获取购物车列表
    getCartList() {
      return this.$apiGetCart().then(result => {
        const { status, data } = result;
        if (status === 0) {
          this.list = data;
          return Promise.resolve(null);
        }
        return Promise.reject(null);
      });
    },
    // 添加到收藏
    addToLike(data) {
      return new Promise(resolve => {
        this.$apiCartToLike({ cartList: data })
          .then(res => {
            const { status, msg } = res;
            if (status === 0) {
              this.$toast({
                message: msg,
                type: "success"
              });
            }
          })
          .finally(() => {
            resolve();
          });
      });
    },
    // 购物车数量修改
    cartNumChange(c, num) {
      if (c.num === num) return;
      const loading = this.$helperLoadding();
      this.$apiUpdateCartNum({ num, cart_id: c.cart_id })
        .then(res => {
          const { status, data } = res;
          if (status === 0) {
            c.num = data;
          }
        })
        .finally(() => {
          loading.clear();
        });
    },
    // 删除购物车
    delCart(data) {
      const cart_ids = data.map(i => i.cart_id);
      return new Promise(resolve => {
        this.$apiDelCart({ cart_ids })
          .then(res => {
            const { status, msg } = res;
            if (status === 0) {
              this.$toast({
                message: msg,
                type: "success"
              });
            }
          })
          .finally(() => {
            resolve();
          });
      });
    },
    // 跳转 订单确认页
    goOrder(data) {
      this.$router.push({
        name: "order-stay",
        params: { list: data, type: "cart" }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.cart-container {
  padding: 50px 0 90px;
  height: 100vh;
  background: #f7f7f7;
  box-sizing: border-box;
  overflow: auto;
  ::v-deep .empty {
    padding-top: 20px;
  }
  .total {
    position: fixed;
    display: flex;
    padding: 0 10px;
    align-items: center;
    justify-content: space-between;
    bottom: 50px;
    left: 0;
    right: 0;
    height: 40px;
    background: #fff;
    font-size: 14px;
    .result {
      display: flex;
      align-items: center;
      big {
        color: red;
      }
    }
    .btn {
      margin-left: 10px;
      height: 30px;
    }
    .delete {
      display: flex;
      align-items: center;
    }
  }
  .right-botton {
    position: absolute;
    top: 12.5px;
    right: 12.5px;
    padding: 2px 8px;
    font-size: 14px;
    border-radius: 12px;
    border: 1px solid #ff976a;
    &.active {
      border-color: #fff;
    }
    ::v-deep .van-icon {
      font-size: 12px;
      vertical-align: text-top;
    }
  }
  .empty-list {
    padding-top: 50px;
  }
}
.cart-list {
  font-size: 16px;
  padding: 20px 10px;
  a {
    color: #000;
  }
  li {
    background: #fff;
    margin-bottom: 20px;
    border-radius: 10px;
  }

  .head {
    padding: 10px 10px 0;
    display: flex;
    font-weight: bold;
    margin-bottom: 5px;
    ::v-deep .van-icon-arrow {
      vertical-align: middle;
    }
    a {
      margin-left: 10px;
    }
  }
  .content {
    width: 170px;
  }

  .item {
    display: flex;
    padding: 10px;
    margin-bottom: 10px;
    font-size: 14px;
    &.disabled {
      background: #f3f3f3;
    }
  }
  .checkbox {
    flex-shrink: 0;
  }
  .info {
    margin-left: 10px;
    display: flex;
    align-items: flex-start;
    color: #000;
    img {
      width: 120px;
      height: 120px;
      margin-right: 10px;
    }
    .name {
      font-weight: 400;
    }
    p {
      margin: 0;
    }
    .spec {
      margin-top: 10px;
      padding: 2px 5px;
      display: inline-block;
      max-width: 160px;
      font-size: 12px;
      background: #e9e9e9;
    }
    .price {
      margin-left: 5px;
      color: red;
      font-size: 16px;
      font-weight: bold;
    }
    .set-num {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
      z-index: 1;
      ::v-deep .van-stepper__input {
        height: 20px;
      }
      ::v-deep button {
        width: 20px !important;
        height: 20px !important;
      }
    }
  }
}
</style>
